<?php
/**
 * Created by PhpStorm.
 * User: lih
 * Date: 2017/6/22
 * Time: 23:09
 */
namespace frontend\api;

use Yii;
use yii\db\Query;
use common\models\User;
use ReflectionClass;

class ApiHandler
{
    public function __construct()
    {
    }

    /**
     * @param string $req
     * @return mixed
     */
    public function handleAction($arrayData)
    {
        $returnData = array();

        $actionStr = '';
        try {
            $actionStr = $arrayData['action'];
            $returnData['action'] = $actionStr;
            $returnData['code'] = '1';
            $returnData['msg'] = '请求出错';

            $this->doSessionOpen(@$arrayData['sessionid']);
            $returnData['sessionid'] = Yii::$app->session->getId();

            $klassName = ucfirst($actionStr);
            if(!empty($klassName)) {
                $refClass = new ReflectionClass('frontend\\api\\action\\'.$klassName);
                $refInstance = $refClass->newInstance();
                $methodRunAction = $refClass->getmethod('runAction');
                $methodRunAction->invokeArgs($refInstance, array($arrayData, &$returnData));
            }
        } catch(\Exception $e) {
            Yii::error("action exception {$actionStr}: {$e->getMessage()}");
        }

        if($returnData === null) {
            $returnData = array();
        }

        return $returnData;
    }

    public function doSessionOpen($sessionId)
    {
        if(!empty($sessionId)) {
            session_id($sessionId);
            Yii::$app->session->open();
        } else {
            Yii::$app->session->open();
            Yii::$app->session->regenerateID(false);
        }
    }
}

